<script lang="ts" setup>
import { reactive, ref, shallowRef, onMounted, defineAsyncComponent } from 'vue'
import { useMap } from '@/hooks/useMap'
import SearchPlace from '@/components/map/SearchPlace.vue'
import { queryBoxLocationsResponseData } from '@/api/cabinet/types/cabinet'
const CabinetTypeFilter = defineAsyncComponent(
  () => import('@/components/map/CabinetTypeFilter.vue')
)
defineOptions({
  name: 'CabinetAMap'
})
const center = reactive({
  longtitude: 0,
  latitude: 0
})
const isInit = ref<boolean>(false)
const mapContainer = ref<HTMLDivElement>()
const massmarks = shallowRef<AMap.MassMarks>()
const infoWindow = shallowRef<AMap.InfoWindow>()
const { map, auto, initAmap, placeSearch } = useMap(mapContainer, [
  center.longtitude,
  center.latitude
])
interface dataType extends queryBoxLocationsResponseData {
  lnglat: [number, number]
  style: number
}
const mapData = ref<dataType[]>([])
const getData = (data: queryBoxLocationsResponseData[]) => {
  mapData.value = data.map((cabinet) => {
    return {
      lnglat: [cabinet.longtitude, cabinet.latitude],
      ...cabinet,
      style: cabinet.masterPowerLevel
    }
  })
  handleClearMap()
  handleCoverInit()
}
const sortImageList = (a: string, b: string) => {
  return getImageNumber(a) - getImageNumber(b)
}
const getImageNumber = (data: string) => {
  const arr = data.split('/')
  const lastsplit = arr[arr.length - 1]
  const imageNumber = Number(lastsplit.split('.')[0])
  return imageNumber
}
const imageAfterList = reactive(
  Object.values(import.meta.glob('@/assets/map/cabinetPowerAfterClick/*.*', { eager: true }))
    .map((v: any) => v.default)
    .sort(sortImageList)
)
const imageBeforeList = reactive(
  Object.values(import.meta.glob('@/assets/map/cabinetPowerBeforeClick/*.*', { eager: true }))
    .map((v: any) => v.default)
    .sort(sortImageList)
)
/** 地图初始化 */
const init = async () => {
  isInit.value = await initAmap()
  handleCoverInit()
}
const handleCoverInit = async () => {
  if (isInit.value && map.value && mapData.value.length > 0) {
    const firtstData = mapData.value[0]
    center.longtitude = firtstData.longtitude
    center.latitude = firtstData.latitude
    map.value?.setCenter([center.longtitude, center.latitude])
    massmarks.value = new AMap.MassMarks(mapData.value, {
      style: getStyle()
    })
    infoWindow.value = new AMap.InfoWindow({
      isCustom: true,
      autoMove: true,
      offset: new AMap.Pixel(25, 8)
    })
    massmarks.value?.setMap(map.value)
    massmarks.value.on('click', handleMassMarkerClick)
    const mapContainer = document.getElementById('map-container')
    mapContainer?.addEventListener('click', handleInfoWindowClick)
  }
}
const handleInfoWindowClick = (event: any) => {
  // 检查是否点击了 "添加工单" 按钮
  if (event.target.className.includes('red-refresh')) {
    refresh()
  }
}
const handleMassMarkerClick = (e: any) => {
  const index = mapData.value.findIndex((item) => item.boxId === e.data.boxId)
  if (infoWindow.value?.getIsOpen()) {
    if (
      infoWindow.value?.getExtData()[0] === e.data.lnglat[0] &&
      infoWindow.value?.getExtData()[1] === e.data.lnglat[1]
    ) {
      infoWindow.value?.close()
      mapData.value[index].style = e.data.style - 101
      massmarks.value?.setData(mapData.value)
    } else {
      mapData.value[index].style = e.data.style + 101
      const infowindowIndex = mapData.value.findIndex(
        (item) =>
          item.lnglat[1] === infoWindow.value?.getExtData()[1] &&
          item.lnglat[0] === infoWindow.value?.getExtData()[0]
      )
      mapData.value[infowindowIndex].style -= 101
      infoWindow.value?.open(map.value!, e.data.lnglat)
      infoWindow.value?.setContent(createContent(e.data))
      infoWindow.value?.setExtData(e.data.lnglat)
      massmarks.value?.setData(mapData.value)
    }
  } else {
    mapData.value[index].style = e.data.style + 101
    massmarks.value?.setData(mapData.value)
    infoWindow.value?.setContent(createContent(e.data))
    infoWindow.value?.setExtData(e.data.lnglat)
    infoWindow.value?.open(map.value!, e.data.lnglat)
  }
}
const handleClearMap = () => {
  if (massmarks.value) {
    massmarks.value.setMap(null)
  }
  if (infoWindow.value) {
    infoWindow.value.close()
  }
}
const getStyle = () => {
  const arr = []
  for (let index = 0; index < 101; index++) {
    const style = {
      anchor: new AMap.Pixel(0, 0),
      url: imageBeforeList[index],
      size: new AMap.Size(59, 63)
    }
    arr.push(style)
  }
  for (let index = 0; index < 101; index++) {
    const style = {
      anchor: new AMap.Pixel(0, 0),
      url: imageAfterList[index],
      size: new AMap.Size(59, 63)
    }
    arr.push(style)
  }
  return arr
}
const createContent = (data: dataType) => {
  return `<div class="cabinet-infowindow">
                <div class="cabinet-infowindow__title">
                  <span>电柜位置:${data.address}</span>
                </div>
                <div class="cabinet-infowindow__content">
                  <span>可用:
                    <span class="green">${data.battery48VCanUseCount}</span><span>(48V)</span>
                    <span class="green">${data.battery60VCanUseCount}</span><span>(60V)</span>
                  </span>
                  <span>不可用:
                  <span class="warning">${data.battery48VInvalidCount}</span><span>(48V)</span>
                  <span class="warning">${data.battery60VInvalidCount}</span><span>(60V)</span>
                  </span>
                </div>
              </div>`
}
const refresh = () => {}
onMounted(() => {
  init()
})
</script>

<template>
  <div class="xy-map-container">
    <div ref="mapContainer" id="map-container">
      <search-place :auto="auto" :map="map!" :place-search="placeSearch" />
      <cabinet-type-filter @get="getData" />
    </div>
  </div>
</template>

<style scoped lang="scss">
:deep(.cabinet-infowindow) {
  background: #ffffff;
  border-radius: 5px 5px 5px 5px;
  padding: 10px;
  .cabinet-infowindow__title {
    font-family:
      PingFang SC,
      PingFang SC;
    font-size: 14px;
    color: rgba(51, 51, 51, 0.99);
    line-height: 22px;
    .red-refresh {
      color: #ff6d75;
    }
  }
  .cabinet-infowindow__content {
    background: #f5f5f5;
    border-radius: 5px 5px 5px 5px;
    margin-top: 5px;
    padding: 10px;
    font-family:
      PingFang SC,
      PingFang SC;
    font-size: 12px;
    color: #999999;
    line-height: 20px;
    display: flex;
    align-items: center;
    > span {
      margin-right: 20px;
    }
    .green {
      color: #07c160;
      font-size: 14px;
    }
    .warning {
      color: #f39939;
      font-size: 14px;
    }
  }
}
</style>
